<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>消息管理 - 企业官网后台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .status-pending { color: #ffc107; }
        .status-read { color: #17a2b8; }
        .status-replied { color: #28a745; }
        .message-preview { 
            max-width: 200px; 
            overflow: hidden; 
            text-overflow: ellipsis; 
            white-space: nowrap; 
        }
        .admin-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
        }
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 1.5rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 1rem;
        }
        .message-card {
            border-left: 4px solid #007bff;
            margin-bottom: 1rem;
        }
        .message-card.status-pending { border-left-color: #ffc107; }
        .message-card.status-read { border-left-color: #17a2b8; }
        .message-card.status-replied { border-left-color: #28a745; }
    </style>
</head>
<body>
    <!-- 头部 -->
    <div class="admin-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col">
                    <h1><i class="bi bi-envelope"></i> 消息管理中心</h1>
                    <p class="mb-0">企业官网联系消息管理</p>
                </div>
                <div class="col-auto">
                    <span class="badge bg-light text-dark fs-6">总计: <span th:text="${totalCount}">0</span> 条消息</span>
                </div>
            </div>
        </div>
    </div>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-3">
                <div class="stats-card">
                    <h5><i class="bi bi-graph-up"></i> 统计信息</h5>
                    <div class="row text-center">
                        <div class="col-4">
                            <div class="text-warning">
                                <i class="bi bi-clock fs-3"></i>
                                <div class="small">待处理</div>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="text-info">
                                <i class="bi bi-eye fs-3"></i>
                                <div class="small">已查看</div>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="text-success">
                                <i class="bi bi-check-circle fs-3"></i>
                                <div class="small">已回复</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 筛选器 -->
                <div class="stats-card">
                    <h5><i class="bi bi-funnel"></i> 筛选条件</h5>
                    <form method="get" action="/admin/messages">
                        <div class="mb-3">
                            <label class="form-label">状态筛选</label>
                            <select name="status" class="form-select">
                                <option value="all" th:selected="${currentStatus == 'all'}">全部消息</option>
                                <option value="PENDING" th:selected="${currentStatus == 'PENDING'}">待处理</option>
                                <option value="READ" th:selected="${currentStatus == 'READ'}">已查看</option>
                                <option value="REPLIED" th:selected="${currentStatus == 'REPLIED'}">已回复</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">每页显示</label>
                            <select name="size" class="form-select">
                                <option value="10">10条</option>
                                <option value="20" selected>20条</option>
                                <option value="50">50条</option>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="bi bi-search"></i> 筛选
                        </button>
                    </form>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="col-md-9">
                <!-- 消息列表 -->
                <div class="row" th:if="${#lists.isEmpty(messages)}">
                    <div class="col-12">
                        <div class="alert alert-info text-center">
                            <i class="bi bi-inbox fs-1"></i>
                            <h4>暂无消息</h4>
                            <p>当前筛选条件下没有找到任何消息</p>
                        </div>
                    </div>
                </div>

                <div class="row" th:unless="${#lists.isEmpty(messages)}">
                    <div class="col-12" th:each="message : ${messages}">
                        <div class="card message-card status-${message.status.name().toLowerCase()}">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-8">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <h6 class="card-title mb-0">
                                                <i class="bi bi-person"></i> 
                                                <span th:text="${message.name}">姓名</span>
                                                <span class="badge bg-secondary ms-2" th:text="${message.status.name()}">状态</span>
                                            </h6>
                                            <small class="text-muted" th:text="${#temporals.format(message.createdAt, 'yyyy-MM-dd HH:mm')}">时间</small>
                                        </div>
                                        <p class="card-text">
                                            <i class="bi bi-envelope"></i> 
                                            <span th:text="${message.email}">邮箱</span>
                                            <span th:if="${message.phone != null and !message.phone.isEmpty()}">
                                                | <i class="bi bi-phone"></i> 
                                                <span th:text="${message.phone}">电话</span>
                                            </span>
                                        </p>
                                        <p class="card-text message-preview" th:text="${message.message}">消息内容预览...</p>
                                        <div class="small text-muted">
                                            <i class="bi bi-geo-alt"></i> IP: <span th:text="${message.ipAddress}">IP地址</span>
                                            <span class="ms-3">
                                                <i class="bi bi-fingerprint"></i> 设备: 
                                                <code th:text="${#strings.substring(message.deviceFingerprint, 0, 8)}">设备指纹</code>...
                                            </span>
                                        </div>
                                    </div>
                                    <div class="col-md-4 text-end">
                                        <div class="btn-group-vertical" role="group">
                                            <a th:href="@{/admin/message/{id}(id=${message.id})}" 
                                               class="btn btn-outline-primary btn-sm">
                                                <i class="bi bi-eye"></i> 查看详情
                                            </a>
                                            <button class="btn btn-outline-success btn-sm" 
                                                    th:data-message-id="${message.id}"
                                                    data-action="updateStatus"
                                                    data-status="READ">
                                                <i class="bi bi-check"></i> 标记已读
                                            </button>
                                            <button class="btn btn-outline-warning btn-sm" 
                                                    th:data-message-id="${message.id}"
                                                    data-action="updateStatus"
                                                    data-status="REPLIED">
                                                <i class="bi bi-reply"></i> 标记已回复
                                            </button>
                                            <button class="btn btn-outline-danger btn-sm" 
                                                    th:data-device-fingerprint="${message.deviceFingerprint}"
                                                    data-action="blockDevice">
                                                <i class="bi bi-shield-x"></i> 封禁设备
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 分页 -->
                <nav th:if="${totalPages > 1}">
                    <ul class="pagination justify-content-center">
                        <li class="page-item" th:classappend="${!hasPrevious} ? 'disabled'">
                            <a class="page-link" th:href="@{/admin/messages(page=${currentPage - 1}, status=${currentStatus})}">
                                <i class="bi bi-chevron-left"></i> 上一页
                            </a>
                        </li>
                        
                        <li class="page-item" th:each="pageNum : ${#numbers.sequence(1, totalPages)}" 
                            th:classappend="${pageNum == currentPage + 1} ? 'active'">
                            <a class="page-link" th:href="@{/admin/messages(page=${pageNum - 1}, status=${currentStatus})}" 
                               th:text="${pageNum}">1</a>
                        </li>
                        
                        <li class="page-item" th:classappend="${!hasNext} ? 'disabled'">
                            <a class="page-link" th:href="@{/admin/messages(page=${currentPage + 1}, status=${currentStatus})}">
                                下一页 <i class="bi bi-chevron-right"></i>
                            </a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
    </div>

    <!-- 状态更新模态框 -->
    <div class="modal fade" id="statusModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">更新消息状态</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="statusForm">
                        <input type="hidden" id="messageId" name="id">
                        <div class="mb-3">
                            <label class="form-label">状态</label>
                            <select name="status" class="form-select" id="statusSelect">
                                <option value="PENDING">待处理</option>
                                <option value="READ">已查看</option>
                                <option value="REPLIED">已回复</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">管理员备注</label>
                            <textarea name="adminNotes" class="form-control" rows="3" 
                                      placeholder="添加备注信息（可选）"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitStatusUpdate()">更新</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function updateStatus(messageId, status) {
            document.getElementById('messageId').value = messageId;
            document.getElementById('statusSelect').value = status;
            new bootstrap.Modal(document.getElementById('statusModal')).show();
        }

        function submitStatusUpdate() {
            const form = document.getElementById('statusForm');
            const formData = new FormData(form);
            
            fetch(`/admin/message/${formData.get('id')}/status`, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('更新失败: ' + data.message);
                }
            })
            .catch(error => {
                alert('更新失败: ' + error.message);
            });
        }

        function blockDevice(deviceFingerprint) {
            if (confirm('确定要封禁此设备24小时吗？')) {
                const formData = new FormData();
                formData.append('deviceFingerprint', deviceFingerprint);
                formData.append('hours', '24');
                
                fetch('/admin/device/block', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('设备已封禁');
                        location.reload();
                    } else {
                        alert('封禁失败: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('封禁失败: ' + error.message);
                });
            }
        }

        // 添加事件监听器处理按钮点击
        document.addEventListener('DOMContentLoaded', function() {
            // 处理状态更新按钮
            document.querySelectorAll('[data-action="updateStatus"]').forEach(button => {
                button.addEventListener('click', function() {
                    const messageId = this.dataset.messageId;
                    const status = this.dataset.status;
                    updateStatus(messageId, status);
                });
            });

            // 处理设备封禁按钮
            document.querySelectorAll('[data-action="blockDevice"]').forEach(button => {
                button.addEventListener('click', function() {
                    const deviceFingerprint = this.dataset.deviceFingerprint;
                    blockDevice(deviceFingerprint);
                });
            });
        });
    </script>
</body>
</html>
